#!/usr/bin/env python
#coding:utf8
# -*- coding: utf-8 -*-  

import os
import sys
import sys,re
import os
import subprocess

CWD = os.getcwd()
# D:\Program Files\Git\bin 
# 把git加入环境变量
BASH_EXEC = 'git-bash.exe'
SPC_ROOT = os.path.join(CWD, 'pack_tools')
SCP_SH = os.path.join(SPC_ROOT, 'scp.sh')

os.chdir('D:\\Program Files\\Git')

#scp file to remote node.
def scpFileToRemoteNode(user,ip,password,localsource,remotedest,port=22):

    # SCP_CMD_BASE = r"""
    #         {bash}
    #         expect -c "
    #         set timeout 300 ;
    #         spawn scp -P {port} -r {localsource} {username}@{host}:{remotedest} ;
    #         expect *assword* {{{{ send {password}\r }}}}  ;
    #         expect *\r ;
    #         expect \r ;
    #         expect eof
    #         "
    # """.format(bash=BASH_EXEC,username=user,password=password,host=ip,localsource=localsource,remotedest=remotedest,port=port)
    # 
    SCP_CMD_BASE = r"""
echo '请主动复制密码粘贴到下面'
echo {password}
scp -P {port} -r {localsource} {username}@{host}:{remotedest}
    """.format(username=user,host=ip,localsource=localsource,remotedest=remotedest,port=port,password=password)
    
    SCP_CMD = SCP_CMD_BASE.format(localsource = localsource)

    with open(SCP_SH, 'w') as f:
        f.write(SCP_CMD)

    print ("execute SCP_CMD:  ",SCP_CMD)

    SCP_CMD = 'git-bash.exe %s/scp.sh' % SPC_ROOT

    try:
        p  = subprocess.Popen( SCP_CMD , stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        p.communicate()

        #os.system(SCP_CMD)
        pass
    except Exception as e:
        print ('error %s' % e)
        pass


def useage():
    print ('------------------------------------------------------')
    print (u'scputil.py 服务器ip 用户 密码 本地路径 远端路径')
    print (u'scputil.py 119.45.195.29 root Chongqing1504 G:/ftp_test/ /App/AutoUpload/ouyangpeng/I12/')
    print ('------------------------------------------------------')

def main():
    args = sys.argv
    if len(args) <= 5:
        useage()
        return

    host_addr   = args[1]
    user_name   = args[2]
    pass_word   = args[3]
    local_path  = args[4]
    romote_path = args[5]

    local_path = local_path.replace('\\', '/')

    if not os.path.isdir(local_path):
        print ('local_path [%s] not isdir .' % local_path)
        useage()
        return

    scpFileToRemoteNode(user_name,host_addr,pass_word,local_path,romote_path,22)

main()